package com.zusmart.core.bean.support;

import java.util.LinkedHashSet;
import java.util.Set;

import com.zusmart.core.bean.BeanDefinition;
import com.zusmart.core.bean.cause.BeanInstanceCreateException;
import com.zusmart.core.bean.cause.BeanInstanceDestoryException;
import com.zusmart.core.bean.cause.BeanInstanceReleaseException;

public class BeanInstanceHandlerForPrototype extends AbstractBeanInstanceHandler {

	private Set<Object> beanInstances;

	public BeanInstanceHandlerForPrototype(BeanDefinition beanDefinition) {
		super(beanDefinition);
	}

	@Override
	public void doCreate() throws BeanInstanceCreateException {
		this.beanInstances = new LinkedHashSet<Object>();
	}

	@Override
	public void doRelease() throws BeanInstanceReleaseException {
		if (null == this.beanInstances || this.beanInstances.size() == 0) {
			return;
		}
		for (Object beanInstance : this.beanInstances) {
			this.doInovkeDestoryMethods(beanInstance);
		}
	}

	@Override
	public void doDestory() throws BeanInstanceDestoryException {
		this.beanInstances.clear();
		this.beanInstances = null;
	}

	@Override
	public Object getBeanInstance() throws BeanInstanceCreateException {
		try {
			Object beanInstance = this.getBeanDefinition().getBeanInstanceCreator().createBeanInstance();
			this.doInjectFields(beanInstance);
			this.doInjectMethods(beanInstance);
			this.doInvokeInitialMethods(beanInstance);
			this.beanInstances.add(beanInstance);
			return beanInstance;
		} catch (Exception e) {
			throw new BeanInstanceCreateException(e.getMessage());
		}
	}

}